package com.ccx.demo.open.common.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.support.mvc.entity.base.Pager;
import com.support.mvc.entity.base.Param;
import com.support.mvc.entity.base.Result;
import com.support.mvc.enums.Code;
import com.support.mvc.web.IController;
import com.utils.util.Dates;
import com.utils.util.Maps;
import com.utils.util.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.concurrent.ExecutorService;

/**
 * 测试接口
 *
 *
 * @author 谢长春 on 2017-9-18
 */
@RequestMapping("/open/test/{version}")
@Controller
@Slf4j
@Validated
public class OpenTestController implements IController<String> {

    @Autowired
    private ExecutorService multiThread;

    @GetMapping("/thymeleaf")
    public String thymeleaf(ModelMap model) {
        model.addAttribute("id", Util.uuid());
        model.addAttribute("name", "JX");
        model.addAttribute("zh", "谢");
        model.addAttribute("timestamp", Dates.now().formatDateTime());
        return "/static/thymeleaf";
    }

    @GetMapping("/codes")
    @ResponseBody
    public Result<?> codes(@PathVariable final int version) {
        final LinkedHashMap<String, String> map = new LinkedHashMap<>();
        for (Code code : Code.values()) {
            map.put(code.name(), code.comment);
        }
        return new Result<>(1).setSuccess(map);
    }

    @PostMapping
    @ResponseBody
    @Override
    public Result<?> save(@PathVariable final int version, @RequestBody(required = false) Param param) {
        return new Result<>(1)
                .execute(result -> {
                    result
                            .setCode(Code.SUCCESS) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                            .setSuccess(Param.of(param).parseObject())
                            .setExtras(Param.of(param).parseObject())
                            .setException("参数解析成功，在data和extras都反回了参数")
                    ;
                });
    }

    @PutMapping("/{id}")
    @ResponseBody
    @Override
    public Result<?> update(@PathVariable final int version, @PathVariable final String id, @RequestBody(required = false) Param param) {
        return new Result<>(1)
                .execute(result -> {
                    JSONObject obj = Param.of(param).parseObject();
                    obj.put("id", id);
                    result
                            .setCode(Code.SUCCESS) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                            .setSuccess(obj)
                            .setExtras(JSON.parseObject(obj.toJSONString()))
                            .setException("参数解析成功，在data和extras都反回了参数，数据ID：" + id)
                    ;
                });
    }

    @DeleteMapping("/{id}")
    @ResponseBody
    @Override
    public Result<?> deleteById(@PathVariable final int version, @PathVariable final String id) {
        return new Result<>(1)
                .execute(result ->
                        result
                                .setCode(Code.SUCCESS) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                                .setSuccess(Maps.ofSS().put("id", id).buildJSONObject())
                                .setExtras(Maps.ofSS().put("id", id).buildJSONObject())
                                .setException(String.format("物理删除ID为【%s】的数据", id))
                );
    }

    @PatchMapping("/change/{id}")
    @ResponseBody
    public Result<?> updateById(@PathVariable final int version, @PathVariable final String id, @RequestBody(required = false) Param param) {
        return update(version, id, param);
    }

    @PatchMapping("/{id}")
    @ResponseBody
    @Override
    public Result<?> markDeleteById(
            @PathVariable final int version,
            @PathVariable final String id) {
        return new Result<>(1)
                .execute(result -> result
                        .setCode(Code.SUCCESS) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                        .setSuccess(Maps.ofSS().put("id", id).buildJSONObject())
                        .setExtras(Maps.ofSS().put("id", id).buildJSONObject())
                        .setException(String.format("逻辑删除ID为【%s】的数据", id))
                );
    }

    @PatchMapping
    @ResponseBody
    @Override
    public Result<?> markDelete(@PathVariable final int version, @RequestBody(required = false) Param param) {
        return new Result<>(1)
                .execute(result -> {
                    result
                            .setCode(Code.SUCCESS) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                            .setSuccess(Maps.of(String.class, JSONArray.class).put("ids", Param.of(param).hasArray().parseArray()).buildJSONObject())
                            .setExtras(Maps.of(String.class, JSONArray.class).put("ids", Param.of(param).hasArray().parseArray()).buildJSONObject())
                            .setException(String.format("批量逻辑删除ID为【%s】的数据", String.join(",", Param.of(param).hasArray().parseArray(String.class))))
                    ;
                });
    }

    @GetMapping("/{id}")
    @ResponseBody
    @Override
    public Result<?> findById(@PathVariable final int version, @PathVariable final String id) {
        return new Result<>(1)
                .execute(result -> result
                        .setCode(Code.SUCCESS) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                        .setSuccess(Maps.ofSS().put("id", id).buildJSONObject())
                        .setExtras(Maps.ofSS().put("id", id).buildJSONObject())
                        .setException(String.format("查询ID为【%s】的数据", id))
                );
    }

    @GetMapping
    @ResponseBody
    @Override
    public Result<?> search(@PathVariable final int version, @RequestParam(required = false, defaultValue = "{}") final String json) {
        return new Result<>(1)
                .execute(result -> result
                        .setCode(Code.SUCCESS) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                        .setSuccess(Param.of(json).parseObject())
                        .setExtras(Param.of(json).parseObject())
                        .setException("带参查询集合，不分页")
                );
    }

    @GetMapping("/{number}/{size}")
    @ResponseBody
    @Override
    public Result<?> page(
            @PathVariable final int version,
            @PathVariable final int number,
            @PathVariable final int size,
            @RequestParam(required = false, defaultValue = "{}") final String json) {
        return new Result<>(1)
                .execute(result -> result
                        .setCode(Code.SUCCESS) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                        .setSuccess(Param.of(json).parseObject())
                        .setExtras(JSON.parseObject(Pager.builder().number(number).size(size).build().toString()))
                        .setException("带参 + 分页查询集合")
                );
    }

    @GetMapping(value = "/application/xml", produces = {"application/xml"})
    @ResponseBody
    public String getApplicationXml() {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><table><header>表头</header><body><row><cell>第一列</cell><cell>第二列</cell></row><row><cell>第一列</cell><cell>第二列</cell></row></body></table>";
    }

    @GetMapping(value = "/text/xml", produces = {"text/xml"})
    @ResponseBody
    public String getTextXml() {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><table><header><cell>第一列</cell><cell>第二列</cell></header><body><row><cell>第一行-第一列</cell><cell>第一行-第二列</cell></row><row><cell>第二行-第一列</cell><cell>第二行-第二列</cell></row></body></table>";
    }

//    @Autowired
//    private UserRepository userRepository;
//
//    @PreAuthorize("hasRole('ADMIN')")
//    @GetMapping
//    @ResponseBody
//    public List<TabUser> getUsers(){
//        return userRepository.findAll();
//    }
//
//    @PostAuthorize("returnObject.username == principal.username or hasRole('ADMIN')")
//    @GetMapping("/{id}")
//    @ResponseBody
//    public TabUser getUser(@PathVariable String id){
//        return userRepository.findById(id).orElse(null);
//    }
//
//    @PostAuthorize("returnObject.username == principal.username or hasRole('ROLE_ADMIN')")
//    @GetMapping
//    @ResponseBody
//    public TabUser findByUsername(@RequestParam(value = "username") String username){
//        return userRepository.findByUsernameOrPhone(username,username);
//    }
//
}